package com.uinnova.product.eam.service.cj.service.impl;

import com.binary.core.lang.StringUtils;
import com.binary.jdbc.Page;
import com.uinnova.product.eam.comm.model.es.ArchReview;
import com.uinnova.product.eam.feign.workable.FlowableFeign;
import com.uinnova.product.eam.feign.workable.entity.PorcessResponse;
import com.uinnova.product.eam.model.asset.QuestionMsgDTO;
import com.uinnova.product.eam.model.cj.domain.*;
import com.uinnova.product.eam.model.cj.enums.ChapterDataTypeEnum;
import com.uinnova.product.eam.model.cj.enums.QuestionCheckEnum;
import com.uinnova.product.eam.model.cj.enums.QuestionStatusEnum;
import com.uinnova.product.eam.model.cj.request.PlanChapterQuestionAnswerRequest;
import com.uinnova.product.eam.model.cj.request.PlanChapterQuestionRequest;
import com.uinnova.product.eam.model.cj.request.PlanModuleAnnotationRequest;
import com.uinnova.product.eam.model.cj.vo.PlanChapterQuestionVO;
import com.uinnova.product.eam.model.cj.vo.PlanDesignInstanceVO;
import com.uinnova.product.eam.model.cj.vo.QuestionAnswerVO;
import com.uinnova.product.eam.model.constants.Constants;
import com.uinnova.product.eam.service.IEamNoticeService;
import com.uinnova.product.eam.service.cj.dao.ArchReviewDao;
import com.uinnova.product.eam.service.cj.dao.ChapterContextDao;
import com.uinnova.product.eam.service.cj.dao.PlanChapterQuestionDao;
import com.uinnova.product.eam.service.cj.service.*;
import com.uinnova.product.eam.service.exception.BusinessException;
import com.uino.api.client.permission.IUserApiSvc;
import com.uino.bean.permission.base.SysUser;
import com.uino.bean.permission.business.CurrentUserInfo;
import com.uino.bean.permission.business.UserInfo;
import com.uino.bean.permission.query.CSysUser;
import com.uino.dao.util.ESUtil;
import com.uino.util.sys.SysUtil;
import lombok.extern.log4j.Log4j2;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: Lc
 * @create: 2022-03-01 19:53
 */
@Service
@Log4j2
public class PlanChapterQuestionServiceImpl implements PlanChapterQuestionService {

    @Resource
    private PlanChapterQuestionDao planChapterQuestionDao;

    @Resource
    private PlanChapterInstanceService planChapterInstanceService;

    @Resource
    private PlanTemplateChapterService planTemplateChapterService;

    @Resource
    private IUserApiSvc userApiSvc;

    @Resource
    private PlanModuleAnnotationService planModuleAnnotationService;

    @Resource
    @Lazy
    private PlanDesignInstanceService planDesignInstanceService;
    @Autowired
    private ArchReviewDao archReviewDao;

    @Resource
    @Lazy
    private IEamNoticeService eamNoticeService;

    @Resource
    private IUserApiSvc iUserApiSvc;

    @Resource
    private FlowableFeign flowableFeign;

    @Autowired
    private ChapterContextDao chapterContextDao;

    @Override
    public Long saveOrUpdate(PlanChapterQuestion question) {
        // 校验参数
        checkQuestion(question);
        // 新增批注
        PlanModuleAnnotationRequest request = new PlanModuleAnnotationRequest();
        request.setChapterId(question.getPlanChapterId());
        request.setPlanChapterModuleId(question.getPlanChapterContextId());
        request.setAnnotationContent(question.getQuestion());
        request.setProblem(true);
        request.setTaskDefinitionKey(question.getTaskDefinitionKey());
        Long annotationId = planModuleAnnotationService.saveAnnotation(request);

        // 设置状态默认值
        question.setQuestionState(QuestionStatusEnum.NOT_RECTIFIED.getState());
        question.setCheckResult(QuestionCheckEnum.LATER_CHECK.getCode());
        question.setAnnotationId(annotationId);
        this.pushQuestionCreateNotice(question);
        return planChapterQuestionDao.saveOrUpdate(question);
    }

    /**
     * 问题创建推送消息
     * @param question
     */
    private void pushQuestionCreateNotice(PlanChapterQuestion question) {
        List<PlanDesignInstance> planDesignInstances = planDesignInstanceService.getByIds(Collections.singleton(question.getPlanId()));
        if (CollectionUtils.isEmpty(planDesignInstances) || planDesignInstances.get(0) == null) {
            log.info("消息，根据方案id未查询到方案 结束：{}", question.getPlanId());
            return;
        }
        PlanDesignInstance planDesignInstance = planDesignInstances.get(0);
        CurrentUserInfo user = iUserApiSvc.getCurrentUser();
        String submitter = planDesignInstance.getCreatorCode();
        String planName = planDesignInstance.getName();
        PorcessResponse porcessResponse = flowableFeign.getProcessInstanceByProcessInstanceId(question.getProcessInstanceId());
        if (porcessResponse != null && !org.apache.commons.lang.StringUtils.isEmpty(porcessResponse.getProcessStartUserId())) {
            submitter = porcessResponse.getProcessStartUserId();
        }

        String currentUserName = user.getUserName();
        QuestionMsgDTO questionMsgDTO = new QuestionMsgDTO();
        questionMsgDTO.setType("create");
        questionMsgDTO.setSubmitter(submitter);
        questionMsgDTO.setPlanName(planName);
        questionMsgDTO.setCurrentUserName(currentUserName);
        eamNoticeService.questionMsgSave(questionMsgDTO);
    }

    @Override
    public Long saveArchivingQuestion(PlanChapterQuestion question) {
        // 校验参数
        checkQuestion(question);

        if (question.getAnnotationId() == null) {
            throw new BusinessException("批注主键不能为空!");
        }
        // 设置状态默认值
        question.setQuestionState(QuestionStatusEnum.NOT_RECTIFIED.getState());
        question.setCheckResult(QuestionCheckEnum.LATER_CHECK.getCode());
        this.pushQuestionCreateNotice(question);
        Long result = planChapterQuestionDao.saveOrUpdate(question);

        // 修改批注问题状态
        PlanModuleAnnotationRequest request = new PlanModuleAnnotationRequest();
        request.setAnnotationId(question.getAnnotationId());
        request.setProblem(true);
        planModuleAnnotationService.modifyAnnotation(request);
        return result;
    }

    @Override
    public Long saveAnswer(PlanChapterQuestionAnswerRequest request) {
        if (request == null) {
            throw new BusinessException("问题回复参数不能为空");
        }
        if (request.getId() == null) {
            throw new BusinessException("问题主键不能为空!");
        }
        PlanChapterQuestion question = planChapterQuestionDao.getById(request.getId());
        if (request.getState() != null) {
            question.setQuestionState(request.getState());
            if (QuestionCheckEnum.NO_PASS.getCode().equals(question.getCheckResult())) {
                question.setCheckResult(QuestionCheckEnum.LATER_CHECK.getCode());
            }
        }
        if (request.getCheck() != null) {
            question.setCheckResult(request.getCheck());
            /*if (QuestionCheckEnum.NO_PASS.getCode().equals(request.getCheck())) {
                question.setQuestionState(QuestionStatusEnum.NOT_RECTIFIED.getState());
            }*/
        }
        if (!StringUtils.isEmpty(request.getAnswer())) {
            QuestionAnswerVO answer = new QuestionAnswerVO();
            answer.setAnswer(request.getAnswer());
            answer.setAnswerTime(ESUtil.getNumberDateTime());
            UserInfo userInfo = userApiSvc.getUserInfoById(SysUtil.getCurrentUserInfo().getId());
            answer.setUsername(userInfo.getUserName());
            if (CollectionUtils.isEmpty(question.getAnswerList())) {
                List<QuestionAnswerVO> answerList = new ArrayList<>();
                answerList.add(answer);
                question.setAnswerList(answerList);
            } else {
                List<QuestionAnswerVO> answerList = question.getAnswerList();
                answerList.add(answer);
            }
        }
        String msgType = null;
        if (request.getCheck() != null) {
            if (QuestionCheckEnum.PASS.getCode().equals(request.getCheck())) {
                // 验证通过
                msgType = "pass";
            } else if (QuestionCheckEnum.NO_PASS.getCode().equals(request.getCheck())) {
                // 验证不通过
                msgType = "noPass";
            }
        } else if (!QuestionStatusEnum.NOT_RECTIFIED.equals(request.getState())) {
            // 已处理：整改/无需整改/例外问题
            msgType = "correction";
            question.setCorrectionUser(SysUtil.getCurrentUserInfo().getLoginCode());
        }
        this.pushQuestionCorrectionNotice(question, msgType);
        return planChapterQuestionDao.saveOrUpdate(question);
    }

    /**
     * 推送问题 整改/验证通过/验证不通过 消息
     * @param question
     */
    private void pushQuestionCorrectionNotice(PlanChapterQuestion question, String type) {
        List<PlanDesignInstance> planDesignInstances = planDesignInstanceService.getByIds(Collections.singleton(question.getPlanId()));
        if (CollectionUtils.isEmpty(planDesignInstances) || planDesignInstances.get(0) == null) {
            log.info("消息，根据方案id未查询到方案 结束：{}", question.getPlanId());
            return;
        }
        CurrentUserInfo user = iUserApiSvc.getCurrentUser();
        PlanDesignInstance planDesignInstance = planDesignInstances.get(0);
        String planName = planDesignInstance.getName();
        String questionCreateUser = question.getCreator();
        String questionCorrectionUser = question.getCorrectionUser();

        String currentUserName = user.getUserName();
        QuestionMsgDTO questionMsgDTO = new QuestionMsgDTO();
        questionMsgDTO.setType(type);
        questionMsgDTO.setPlanName(planName);
        questionMsgDTO.setCurrentUserName(currentUserName);
        questionMsgDTO.setQuestionCreateUser(questionCreateUser);
        questionMsgDTO.setQuestionCorrectionUser(questionCorrectionUser);
        eamNoticeService.questionMsgSave(questionMsgDTO);
    }

    @Override
    public Page<PlanChapterQuestionVO> findQuestionList(PlanChapterQuestionRequest request) {
        if (request == null) {
            throw new BusinessException("请求参数不能为空!");
        }
        if (request.getPlanId() == null) {
            throw new BusinessException("方案主键不能为空!");
        }
        PlanDesignInstanceVO plan = planDesignInstanceService.getById(request.getPlanId());
        if (plan == null) {
            throw new BusinessException("获取方案错误!");
        }
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        queryBuilder.must(QueryBuilders.termQuery("planId", request.getPlanId()));
        if (!StringUtils.isEmpty(request.getQuestion())) {
            queryBuilder.must(QueryBuilders.wildcardQuery("question.keyword", "*" + request.getQuestion() + "*"));
        }
        // 判断当前登录人是否是提交人，提交人查询所有问题，审批人只查询自己的问题
        if (!Objects.equals(plan.getCreatorCode(), SysUtil.getCurrentUserInfo().getLoginCode())) {
            if (StringUtils.isEmpty(request.getProcessInstanceId())) {
                throw new BusinessException("流程实例不能为空!");
            }
            if (StringUtils.isEmpty(request.getTaskDefinitionKey())) {
                throw new BusinessException("任务定义不能为空!");
            }
            queryBuilder.must(QueryBuilders.termQuery("creator.keyword", SysUtil.getCurrentUserInfo().getLoginCode()));
            queryBuilder.must(QueryBuilders.termQuery("processInstanceId.keyword", request.getProcessInstanceId()));
            queryBuilder.must(QueryBuilders.termQuery("taskDefinitionKey.keyword", request.getTaskDefinitionKey()));
        }
        Page<PlanChapterQuestion> questionPage = planChapterQuestionDao.getSortListByQuery(request.getPageNum(), request.getPageSize(), queryBuilder, "createTime", false);
        List<PlanChapterQuestionVO> questionVoList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(questionPage.getData())) {
            questionPage.getData().forEach(question -> {
                PlanChapterQuestionVO questionVo = new PlanChapterQuestionVO();
                questionVo.setId(question.getId());
                questionVo.setQuestion(question.getQuestion());
                // 问题回复内容
                if (!CollectionUtils.isEmpty(question.getAnswerList())) {
                    List<QuestionAnswerVO> answerList = question.getAnswerList();
                    questionVo.setAnswer(answerList.get(answerList.size() - 1).getAnswer());
                } else {
                    questionVo.setAnswer(Constants.CENTRE_LINE);
                }
                // 回复状态
                questionVo.setQuestionState(QuestionStatusEnum.getQuestionDesc(question.getQuestionState()));
                // 验证功能是否可用
                if (Objects.equals(question.getQuestionState(), QuestionStatusEnum.NOT_RECTIFIED.getState()) && Objects.equals(question.getCheckResult(), QuestionCheckEnum.LATER_CHECK.getCode())) {
                    questionVo.setCheckSign(false);
                } else {
                    questionVo.setCheckSign(true);
                }
                // 验证状态
                questionVo.setCheckResult(QuestionCheckEnum.getCheckDesc(question.getCheckResult()));
                // 章节信息
                ChapterInstance chapterInstance = planChapterInstanceService.getPlanChapterInstance(question.getPlanChapterId());
                // 模板数据内容
                PlanTemplateChapterData chapterData = planTemplateChapterService.getTemplateChapterData(question.getPlanChapterContextId());
                if (chapterInstance != null && !StringUtils.isEmpty(chapterInstance.getName())) {
                    String module = chapterInstance.getName();
                    if (chapterData != null) {
                        if (ChapterDataTypeEnum.PRODUCT.getDataType().equals(chapterData.getType())
                                && !StringUtils.isEmpty(chapterData.getProductName())) {
                            module = module + Constants.SLASH + chapterData.getProductName();
                        } else if (ChapterDataTypeEnum.DATA_TABLE.getDataType().equals(chapterData.getType())
                                && !StringUtils.isEmpty(chapterData.getDataTableName())) {
                            module = module + Constants.SLASH + chapterData.getDataTableName();
                        } else if (ChapterDataTypeEnum.RICH_TEXT.getDataType().equals(chapterData.getType())
                                && !StringUtils.isEmpty(chapterData.getRichTextName())) {
                            module = module + Constants.SLASH + chapterData.getRichTextName();
                        }
                    }
                    questionVo.setModule(module);
                }
                questionVoList.add(questionVo);
            });
        }
        // 重新控制分页
        Page<PlanChapterQuestionVO> page = new Page<>();
        page.setPageNum(questionPage.getPageNum());
        page.setPageSize(questionPage.getPageSize());
        page.setTotalPages(questionPage.getTotalPages());
        page.setTotalRows(questionPage.getTotalRows());
        page.setData(questionVoList);
        return page;
    }

    @Override
    public Page<PlanChapterQuestionVO> findGTQuestionList(PlanChapterQuestionRequest request) {
        if (request == null) {
            throw new BusinessException("请求参数不能为空!");
        }
        if (StringUtils.isBlank(request.getBusinessKey()) && request.getArchReviewId() == null) {
            throw new BusinessException("缺少参数");
        }
        ArchReview archReview;
        if (!StringUtils.isBlank(request.getBusinessKey())) {
            archReview = archReviewDao.getById(Long.valueOf(request.getBusinessKey()));
        } else {
            archReview = archReviewDao.getById(request.getArchReviewId());
        }
        String processInstanceId = "-";
        if (!StringUtils.isBlank(archReview.getProcessInstanceId())) {
            processInstanceId = archReview.getProcessInstanceId();
        }
        Assert.notNull(archReview, "未找到架构评审提交记录");
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        queryBuilder.must(QueryBuilders.termsQuery("planId", archReview.getPlanIds()));
        queryBuilder.must(QueryBuilders.termQuery("processInstanceId.keyword", processInstanceId));
        if (!StringUtils.isEmpty(request.getQuestion())) {
            queryBuilder.must(QueryBuilders.wildcardQuery("question.keyword", "*" + request.getQuestion() + "*"));
        }
        //国投：任何人可以看所有问题
        // 判断当前登录人是否是提交人，提交人查询所有问题，审批人只查询自己的问题
//        if (!Objects.equals(archReview.getCreatorCode(), SysUtil.getCurrentUserInfo().getLoginCode())) {
//            if (StringUtils.isEmpty(request.getProcessInstanceId())) {
//                throw new BusinessException("流程实例不能为空!");
//            }
//            if (StringUtils.isEmpty(request.getTaskDefinitionKey())) {
//                throw new BusinessException("任务定义不能为空!");
//            }
//            queryBuilder.must(QueryBuilders.termQuery("creator.keyword", SysUtil.getCurrentUserInfo().getLoginCode()));
//            queryBuilder.must(QueryBuilders.termQuery("processInstanceId.keyword", request.getProcessInstanceId()));
//            queryBuilder.must(QueryBuilders.termQuery("taskDefinitionKey.keyword", request.getTaskDefinitionKey()));
//        }
        Page<PlanChapterQuestion> questionPage = planChapterQuestionDao.getSortListByQuery(request.getPageNum(), request.getPageSize(), queryBuilder, "createTime", false);
        List<PlanChapterQuestionVO> questionVoList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(questionPage.getData())) {
            Map<Long, PlanDesignInstance> planMap = new HashMap<>();
            List<PlanDesignInstance> plans = planDesignInstanceService.getByIds(archReview.getPlanIds());
            if (!CollectionUtils.isEmpty(plans)) {
                planMap = plans.stream().collect(Collectors.toMap(PlanDesignInstance::getId, Function.identity()));
            }
            Set<String> creatorLoginCodes = questionPage.getData().stream().map(PlanChapterQuestion::getCreator).collect(Collectors.toSet());
            CSysUser cdt = new CSysUser();
            cdt.setLoginCodes(creatorLoginCodes.toArray(new String[creatorLoginCodes.size()]));
            List<SysUser> sysUsers = userApiSvc.getSysUserByCdt(cdt);
            Map<String, SysUser> userMap = new HashMap<>();
            if (!CollectionUtils.isEmpty(sysUsers)) {
                userMap = sysUsers.stream().collect(Collectors.toMap(SysUser::getLoginCode, Function.identity()));
            }
            for (PlanChapterQuestion question : questionPage.getData()) {
                PlanChapterQuestionVO questionVo = new PlanChapterQuestionVO();
                questionVo.setId(question.getId());
                questionVo.setQuestion(question.getQuestion());
                questionVo.setCreator(question.getCreator());
                questionVo.setCreatorName(userMap.containsKey(question.getCreator()) ? userMap.get(question.getCreator()).getUserName() : "-");
                questionVo.setPlanName(planMap.containsKey(question.getPlanId()) ? planMap.get(question.getPlanId()).getName() : "-");
                questionVo.setPlanId(question.getPlanId());
                questionVo.setPlanChapterId(question.getPlanChapterId());
                questionVo.setPlanChapterContextId(question.getPlanChapterContextId());
                // 问题回复内容
                if (!CollectionUtils.isEmpty(question.getAnswerList())) {
                    List<QuestionAnswerVO> answerList = question.getAnswerList();
                    questionVo.setAnswer(answerList.get(answerList.size() - 1).getAnswer());
                } else {
                    questionVo.setAnswer(Constants.CENTRE_LINE);
                }
                // 回复状态
                questionVo.setQuestionState(QuestionStatusEnum.getQuestionDesc(question.getQuestionState()));
                // 验证功能是否可用
                if (Objects.equals(question.getQuestionState(), QuestionStatusEnum.NOT_RECTIFIED.getState()) && Objects.equals(question.getCheckResult(), QuestionCheckEnum.LATER_CHECK.getCode())) {
                    questionVo.setCheckSign(false);
                } else {
                    questionVo.setCheckSign(true);
                }
                // 验证状态
                questionVo.setCheckResult(QuestionCheckEnum.getCheckDesc(question.getCheckResult()));
                // 章节信息
                ChapterInstance chapterInstance = planChapterInstanceService.getPlanChapterInstance(question.getPlanChapterId());
//                // 模板数据内容
//                PlanTemplateChapterData chapterData = planTemplateChapterService.getTemplateChapterData(question.getPlanChapterContextId());
//                if (chapterInstance != null && !StringUtils.isEmpty(chapterInstance.getName())) {
//                    String module = chapterInstance.getName();
//                    if (chapterData != null) {
//                        if (ChapterDataTypeEnum.PRODUCT.getDataType().equals(chapterData.getType())
//                                && !StringUtils.isEmpty(chapterData.getProductName())) {
//                            module = module + Constants.SLASH + chapterData.getProductName();
//                        } else if (ChapterDataTypeEnum.DATA_TABLE.getDataType().equals(chapterData.getType())
//                                && !StringUtils.isEmpty(chapterData.getDataTableName())) {
//                            module = module + Constants.SLASH + chapterData.getDataTableName();
//                        } else if (ChapterDataTypeEnum.RICH_TEXT.getDataType().equals(chapterData.getType())
//                                && !StringUtils.isEmpty(chapterData.getRichTextName())) {
//                            module = module + Constants.SLASH + chapterData.getRichTextName();
//                        }
//                    }
//                    questionVo.setModule(module);
//                }
                if (chapterInstance != null && !StringUtils.isEmpty(chapterInstance.getName())) {
                    String moduleName = chapterInstance.getName();
                    ChapterContext context = chapterContextDao.getById(question.getPlanChapterId());
                    if (!CollectionUtils.isEmpty(context.getModuleList())) {
                        ContextModule module = context.getModuleList().stream()
                                .collect(Collectors.toMap(ContextModule::getId, Function.identity()))
                                .get(question.getPlanChapterContextId());
                        if (module != null) {
                            PlanTemplateChapterData moduleDefinition = module.getModuleDefinition();
                            Integer moduleType = moduleDefinition.getType();
                            // 制品
                            int product = 1;
                            // 表格
                            int table = 2;
                            // 富文本
                            int richText = 3;
                            //清单制品
                            int dataSet = 4;
                            //附件
                            int appendix = 5;
                            if (moduleType == product) {
                                moduleName = moduleName + Constants.SLASH + moduleDefinition.getProductName();
                            } else if (moduleType == table) {
                                moduleName = moduleName + Constants.SLASH + moduleDefinition.getDataTableName();
                            } else if (moduleType == richText) {
                                moduleName = moduleName + Constants.SLASH + moduleDefinition.getRichTextName();
                            } else if (moduleType == dataSet) {
                                moduleName = moduleName + Constants.SLASH + moduleDefinition.getDataSetName();
                            } else if (moduleType == appendix) {
                                moduleName = moduleName + Constants.SLASH + moduleDefinition.getAppendixName();
                            }
                        }
                    }
                    questionVo.setModule(moduleName);
                }
                questionVoList.add(questionVo);
            }

        }
        // 重新控制分页
        Page<PlanChapterQuestionVO> page = new Page<>();
        page.setPageNum(questionPage.getPageNum());
        page.setPageSize(questionPage.getPageSize());
        page.setTotalPages(questionPage.getTotalPages());
        page.setTotalRows(questionPage.getTotalRows());
        page.setData(questionVoList);
        return page;
    }

    @Override
    public List<QuestionAnswerVO> findAnswerList(Long id) {
        if (id == null) {
            throw new BusinessException("主键不能为空!");
        }
        PlanChapterQuestion question = planChapterQuestionDao.getById(id);
        if (question != null) {
            return question.getAnswerList();
        }
        return Collections.emptyList();
    }

    @Override
    public Boolean updateQuestionAndAnnotation(PlanModuleAnnotationRequest request) {
        if (request == null) {
            throw new BusinessException("参数不能为空!");
        }
        if (request.getAnnotationId() == null) {
            throw new BusinessException("批注主键不能为空!");
        }
        if (StringUtils.isEmpty(request.getAnnotationContent())) {
            throw new BusinessException("内容不能为空!");
        }
        // 修改问题
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        queryBuilder.must(QueryBuilders.termQuery("annotationId", request.getAnnotationId()));
        List<PlanChapterQuestion> questionList = planChapterQuestionDao.getListByQuery(queryBuilder);
        if (!CollectionUtils.isEmpty(questionList)) {
            PlanChapterQuestion chapterQuestion = questionList.get(0);
            chapterQuestion.setQuestion(request.getAnnotationContent());
            planChapterQuestionDao.saveOrUpdate(chapterQuestion);
        }

        // 同时修改批注
        PlanModuleAnnotationRequest annotationRequest = new PlanModuleAnnotationRequest();
        annotationRequest.setAnnotationId(request.getAnnotationId());
        annotationRequest.setAnnotationContent(request.getAnnotationContent());
        planModuleAnnotationService.modifyAnnotation(request);
        return true;
    }

    @Override
    public Boolean deleteQuestionAndAnnotation(Long annotationId) {
        if (annotationId == null) {
            throw new BusinessException("批注主键不能为空!");
        }
        // 删除问题
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        queryBuilder.must(QueryBuilders.termQuery("annotationId", annotationId));
        planChapterQuestionDao.deleteByQuery(queryBuilder, true);

        // 同时删除批注
        PlanModuleAnnotationRequest request = new PlanModuleAnnotationRequest();
        request.setAnnotationId(annotationId);
        planModuleAnnotationService.deleteAnnotation(request);
        return true;
    }

    @Override
    public Boolean deleteQuestionAndAnnotationByPlanId(Long planId) {
        if (planId == null) {
            throw new BusinessException("方案主键不能为空!");
        }
        // 删除问题
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        queryBuilder.must(QueryBuilders.termQuery("planId", planId));
        planChapterQuestionDao.deleteByQuery(queryBuilder, true);

        // 删除批注
        planModuleAnnotationService.deleteAnnotationByPlanId(planId);
        return true;
    }

    @Override
    public Boolean cancelArchiving(Long annotationId) {
        if (annotationId == null) {
            throw new BusinessException("批注主键不能为空!");
        }

        // 删除问题
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        queryBuilder.must(QueryBuilders.termQuery("annotationId", annotationId));
        List<PlanChapterQuestion> questionList = planChapterQuestionDao.getListByQuery(queryBuilder);
        if (!CollectionUtils.isEmpty(questionList)) {
            PlanChapterQuestion chapterQuestion = questionList.get(0);
            planChapterQuestionDao.deleteById(chapterQuestion.getId());
        }

        // 设置批注为非问题
        PlanModuleAnnotationRequest request = new PlanModuleAnnotationRequest();
        request.setAnnotationId(annotationId);
        request.setProblem(false);
        planModuleAnnotationService.modifyAnnotation(request);
        return true;
    }

    @Override
    public Long countQuestion(PlanChapterQuestion question) {
        if (question == null) {
            throw new BusinessException("传递参数不能为空!");
        }
        if (question.getPlanId() == null) {
            throw new BusinessException("方案主键不能为空!");
        }
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        queryBuilder.must(QueryBuilders.termQuery("planId", question.getPlanId()));
        if (question.getQuestionState() != null) {
            queryBuilder.must(QueryBuilders.termQuery("questionState", question.getQuestionState()));
        }
        if (question.getCheckResult() != null) {
            queryBuilder.mustNot(QueryBuilders.termQuery("checkResult", question.getCheckResult()));
        }
        if (!StringUtils.isEmpty(question.getCreatorCode())) {
            queryBuilder.must(QueryBuilders.termQuery("creator.keyword", question.getCreatorCode()));
        }
        if (!StringUtils.isEmpty(question.getProcessInstanceId())) {
            queryBuilder.must(QueryBuilders.termQuery("processInstanceId.keyword", question.getProcessInstanceId()));
        }
        if (!StringUtils.isEmpty(question.getTaskDefinitionKey())) {
            queryBuilder.must(QueryBuilders.termQuery("taskDefinitionKey.keyword", question.getTaskDefinitionKey()));
        }
        return planChapterQuestionDao.countByCondition(queryBuilder);
    }

    private void checkQuestion(PlanChapterQuestion question) {
        if (question == null) {
            throw new BusinessException("问题参数不能为空!");
        }
        if (question.getPlanId() == null) {
            throw new BusinessException("方案主键不能为空!");
        }
        if (question.getPlanChapterId() == null) {
            throw new BusinessException("方案章节不能为空!");
        }
        if (question.getPlanChapterContextId() == null) {
            throw new BusinessException("方案章节内容不能为空!");
        }
        if (question.getQuestion() == null) {
            throw new BusinessException("问题不能为空!");
        }
        if (question.getTaskDefinitionKey() == null) {
            throw new BusinessException("任务定义主键");
        }
    }

}
